import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";

// Log configuration for debugging
console.log("AWS Config:", {
  region: process.env.REACT_APP_AWS_REGION,
  bucket: process.env.REACT_APP_S3_BUCKET_NAME,
  cloudfront: process.env.REACT_APP_CLOUDFRONT_URL,
});

const s3Client = new S3Client({
  region: process.env.REACT_APP_AWS_REGION,
  credentials: {
    accessKeyId: process.env.REACT_APP_AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.REACT_APP_AWS_SECRET_ACCESS_KEY,
  },
});

const constructCloudfrontUrl = (key) => {
  // Remove any leading slashes
  const cleanKey = key.replace(/^\/+/, "");
  // Ensure the CloudFront URL doesn't end with a slash
  const baseUrl = process.env.REACT_APP_CLOUDFRONT_URL.replace(/\/+$/, "");
  return `${baseUrl}/${cleanKey}`;
};

export const uploadImageToS3 = async (file) => {
  try {
    // Log file details for debugging
    console.log("Uploading file:", {
      name: file.name,
      type: file.type,
      size: file.size,
    });

    // Convert file to buffer
    const buffer = await file
      .arrayBuffer()
      .then((arrayBuffer) => new Uint8Array(arrayBuffer));

    // Generate a unique filename with proper path
    const fileName = `images/${Date.now()}-${file.name.replace(
      /[^a-zA-Z0-9.-]/g,
      ""
    )}`;

    const command = new PutObjectCommand({
      Bucket: process.env.REACT_APP_S3_BUCKET_NAME,
      Key: fileName,
      Body: buffer,
      ContentType: file.type,
      CacheControl: "max-age=31536000", // Cache for 1 year
      Metadata: {
        "original-filename": file.name,
        "upload-date": new Date().toISOString(),
      },
    });

    console.log("Starting upload to S3...");
    const result = await s3Client.send(command);
    console.log("Upload successful:", result);

    // Generate CloudFront URL
    const cloudfrontUrl = constructCloudfrontUrl(fileName);
    console.log("Generated CloudFront URL:", cloudfrontUrl);

    return cloudfrontUrl;
  } catch (error) {
    console.error("Detailed upload error:", {
      message: error.message,
      code: error.code,
      requestId: error.$metadata?.requestId,
      details: error.toString(),
    });
    throw new Error(`Failed to upload image: ${error.message}`);
  }
};
